package com.webdrider.servlet.action.blog;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractValidator;
import com.common.model.validators.ActionValidator;
import com.common.security.errors.ParserError;
import com.common.security.exceptions.ManagerException;
import com.common.security.exceptions.ParserException;
import com.common.servlet.abstracts.AbstractParserServlet;
import com.common.servlet.interfaces.IParser;
import com.webdrider.manager.action.blog.PostManager;
import com.webdrider.manager.interfaces.IPostManager;
import com.webdrider.model.action.blog.Post;
import com.webdrider.model.requests.blog.AddBlogPostRequest;
import com.webdrider.model.response.blog.AddBlogPostResponse;
import com.webdrider.model.validators.AdminValidator;
import com.webdrider.model.validators.SessionValidator;
import com.webdrider.servlet.util.RequestAction;
import com.webdrider.servlet.util.parser.blog.AddBlogPostXMLParser;

public class AddBlogPostServlet extends AbstractParserServlet {
	private static final long serialVersionUID = 1L;
	private static Set<AbstractValidator> validators = new HashSet<AbstractValidator>();
	
	private AddBlogPostRequest requestContent;
	private AddBlogPostXMLParser parser = new AddBlogPostXMLParser();
	private IPostManager postManager = new PostManager();
	
	static {
		validators.add(new ActionValidator(RequestAction.ADD_BLOG_POST));
		validators.add(new SessionValidator());
		validators.add(new AdminValidator());
	}

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response) {
		try {
			AddBlogPostResponse addBlogPostResponse = new AddBlogPostResponse();
			
			Post post = requestContent.getPost();
			postManager.save(post);
			
			addBlogPostResponse.setRequestAction(requestContent.getAction());
			
			response.setContentType("text/xml");
			response.getWriter().write(parser().parseResponse(addBlogPostResponse));
			response.getWriter().close();
		} catch (ManagerException managerException) {
			exception(managerException, response);
		} catch (ParserException parserException) {
			exception(parserException, response);
		} catch (IOException ioException) {
			error(new ParserError(ParserError.STREAM_ERROR), response);
		}
	}

	@Override
	public void setRequest(AbstractRequest abstractRequest) {
		requestContent = (AddBlogPostRequest) abstractRequest;
	}

	@Override
	public Set<AbstractValidator> getValidators() {
		return validators;
	}

	@Override
	public IParser parser() {
		return parser;
	}
}
